<template>
  <div>
    <van-popup
      round
      v-model:show="show"
      position="bottom"
      :style="{ height: '80%' }"
      :close-on-click-overlay="true"
    >
      <div class="popup-box">
        <ul>
          <li
            class="item"
            v-for="item in operationList"
            :key="item.value"
            @click="handleOperationSelect(item)"
          >
            {{ item.text }}
          </li>
        </ul>
      </div>
    </van-popup>
    <!-- 这里可以跟另外的弹窗，不做跳转 -->
    <MemberInfoPopup
      ref="memberInfoPopupRef"
      :uid="info?.UserId || null"
      @update="emit('updateData')"
    >
    </MemberInfoPopup>
    <MemberPwdPopup ref="memberPwdPopupRef" :uid="info?.UserId || null" @update="updateAndClose" />

    <MemberBackwaterPopup
      ref="memberBackwaterPopup"
      :uid="info?.UserId || undefined"
      :username="info?.Name"
      :is-special-backwater="info?.IsSpecialBackwater"
    ></MemberBackwaterPopup>

    <MemberReportDetailPopup
      ref="memberReportDetailPopup"
      :uid="info?.UserId || undefined"
      :name="info?.Name"
    />

    <MemberPointPopup
      ref="memberPointPopup"
      :uid="info?.UserId"
      :username="info?.Name"
      @update="emit('updateData')"
    >
    </MemberPointPopup>

    <MemberRedPacketPopup
      ref="memberRedPacketPopup"
      type="add"
      :uid="info?.UserId"
      :username="info?.Name"
    />

    <van-dialog
      v-model:show="sendMessageState.show"
      :title="sendMessageState.title"
      show-cancel-button
      :beforeClose="handleSendMessageBeforeClose"
    >
      <van-field
        v-model="sendMessageState.message"
        label-width="0"
        placeholder="请输入消息内容"
        type="textarea"
      />
    </van-dialog>
  </div>
</template>
<script setup lang="ts">
import { toast } from "@/utils/toast";
import MemberInfoPopup from "./member-info-popup.vue";
import MemberPwdPopup from "./member-pwd-popup.vue";
import { showDialog, showSuccessToast } from "vant";
import {
  reqUserDel,
  reqUserBan,
  reqUserUpdateWithdrawPassword,
  reqUserChatSendMsg,
  reqUserBehalf,
  reqUserBecomeAgent
} from "@/api/user";
import MemberPointPopup from "./member-point-popup.vue";

import MemberReportDetailPopup from "./member-report-detail-popup.vue";
import MemberRedPacketPopup from "./member-red-packet-popup.vue";

import MemberBackwaterPopup from "./member-backwater-popup.vue";
import { usePremsStore } from "@/store/modules/prems";

const props = withDefaults(
  defineProps<{
    info: MemberMo | null;
  }>(),
  {}
);
const emit = defineEmits<{
  (event: "updateData"): void;
}>();

const sendMessageState = reactive({
  show: false,
  title: "",
  message: ""
});

const handleSendMessageBeforeClose = async (action: "confirm" | "cancel") => {
  if (action == "confirm") {
    if (sendMessageState.message.trim()) {
      try {
        await reqUserChatSendMsg({
          UserId: Number(props.info?.UserId),
          Msg: sendMessageState.message
        });
        toast.success("发送成功");
        return true;
      } catch (error) {
        return false;
      }
    }
    toast.fail("请输入消息内容");
    return false;
  } else {
    sendMessageState.message = "";
    sendMessageState.title = "";
    sendMessageState.show = false;
    return true;
  }
};

const premsStore = usePremsStore();
const memberInfoPopupRef = ref();
const memberPwdPopupRef = ref();
const memberBackwaterPopup = ref();
const memberReportDetailPopup = ref();
const memberPointPopup = ref();
const memberRedPacketPopup = ref();

const show = ref(false);
const operationList = computed(() => {
  const IsBehalf = props.info?.IsBehalf;
  const list = [
    { text: "会员资料", value: "member-info" },
    { text: "私信", value: "chat" },
    { text: "回水比例", value: "backwater" },
    { text: "报表详情", value: "detail" },
    { text: "分数操作", value: "updown" },
    { text: "发红包", value: "red" },
    { text: "设置代理", value: "agent" },
    {
      text: IsBehalf == 1 ? "取消代注" : "设置代注",
      value: IsBehalf == 1 ? "cancel_behalf" : "behalf"
    },
    { text: "修改密码", value: "setpass" },
    { text: "重置下分密码", value: "resetpass" }
  ];
  const Status = props.info?.Status;
  if (Status === 2) {
    list.push({ text: "解除禁言", value: "cancel_forbidden" });
  } else {
    list.push({ text: "禁言", value: "forbidden" });
  }
  if (Status === 1) {
    list.push({ text: "禁止加入房间", value: "banroom" });
  } else {
    list.push({ text: "解除禁止加入房间", value: "cancel_banroom" });
  }
  list.push({ text: "删除用户", value: "delete" });
  return list;
});

const handleOperationSelect = (item: { text: string; value: string }) => {
  switch (item.value) {
    case "member-info":
      memberInfoPopupRef.value?.open();
      break;
    case "chat":
      sendMessageState.title = `私信：【${props.info?.Nickname}】`;
      sendMessageState.message = "";
      sendMessageState.show = true;
      break;
    case "backwater":
      memberBackwaterPopup.value?.open();
      break;
    case "detail":
      memberReportDetailPopup.value?.open();
      break;
    case "updown":
      memberPointPopup.value?.open();
      break;
    case "red":
      memberRedPacketPopup.value?.open();
      break;
    case "agent":
      handleAgent();
      break;
    case "behalf":
    case "cancel_behalf":
      handleBehalf();
      break;
    case "setpass":
      memberPwdPopupRef.value?.open();
      break;
    case "resetpass":
      resetPass();
      break;
    case "forbidden":
      forbidden(2);
      break;
    case "cancel_forbidden":
      forbidden(1);
      break;
    case "cancel_banroom":
      handleBanJoinRoom(1);
      break;
    case "banroom":
      handleBanJoinRoom(3);
      break;
    case "delete":
      handleDelete();
      break;
    default:
      break;
  }
  show.value = false;
};

const beforeClose: any = (action: string) => {
  return new Promise(resolve => {
    // 这里处理确认和取消操作
    resolve(action === "confirm" || action === "cancel");
  });
};

const doConfirm = async (callback: Function, text: string) => {
  try {
    await showDialog({
      title: "提示",
      message: text,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      beforeClose,
      showCancelButton: true
    });
    await callback();
  } catch (error) {
    console.log("操作被取消或失败", error);
  }
};

const handleDelete = () => {
  if (!premsStore.isEditUserSetting) {
    toast.info("暂无权限");
    return;
  }
  doConfirm(async () => {
    if (!props.info?.UserId) return;
    await reqUserDel(props.info.UserId);
    showSuccessToast("删除成功");
    show.value = false;
    emit("updateData");
  }, "是否进行【删除用户】操作？");
};

const handleBanJoinRoom = (Status: 0 | 1 | 2 | 3) => {
  if (!premsStore.isEditUserSetting) {
    toast.info("暂无权限");
    return;
  }
  doConfirm(
    async () => {
      if (!props.info?.UserId) return;
      const payload = {
        UserId: props.info.UserId,
        Status: Status
      };
      await reqUserBan(payload);
      showSuccessToast(Status == 3 ? "禁止加入房间成功" : "解除禁止加入房间成功");
      show.value = false;
      emit("updateData");
    },
    Status == 3 ? "是否进行【禁止加入房间】操作？" : "是否进行【解除禁止加入房间】操作？"
  );
};

// 禁言操作
const forbidden = async (Status: 0 | 1 | 2 | 3) => {
  if (!premsStore.isEditUserSetting) {
    toast.info("暂无权限");
    return;
  }
  doConfirm(
    async () => {
      if (!props.info?.UserId) return;
      const payload = {
        UserId: props.info.UserId,
        Status: Status
      };
      await reqUserBan(payload);
      showSuccessToast(Status == 2 ? "禁言成功" : "解除禁言成功");
      show.value = false;
      emit("updateData");
    },
    Status == 2 ? "是否进行【禁言】操作？" : "是否进行【解除禁言】操作？"
  );
};

// 重置下分密码
const resetPass = async () => {
  if (!premsStore.isEditUserSetting) {
    toast.info("暂无权限");
    return;
  }
  doConfirm(async () => {
    if (!props.info?.UserId) return;
    await reqUserUpdateWithdrawPassword(props.info.UserId);
    showSuccessToast("重置下分密码成功");
    show.value = false;
    emit("updateData");
  }, "是否进行【重置下分密码】操作？");
};

const handleBehalf = async () => {
  if (!premsStore.isEditUserSetting) {
    toast.info("暂无权限");
    return;
  }
  if (!props.info?.UserId) return;
  const { UserId, IsBehalf } = props.info;
  doConfirm(
    async () => {
      const payload = {
        UserId: UserId,
        IsBehalf: IsBehalf == 1 ? 0 : 1
      };
      await reqUserBehalf(payload);
      showSuccessToast(payload.IsBehalf == 1 ? "取消代注成功" : "设置代注成功");
      show.value = false;
      emit("updateData");
    },
    IsBehalf == 1 ? "是否取消该会员为代注会员？" : "是否设置该会员为代注会员？"
  );
};

const handleAgent = async () => {
  if (!premsStore.isEditUserSetting) {
    toast.info("暂无权限");
    return;
  }
  doConfirm(async () => {
    if (!props.info?.UserId) return;
    const payload = {
      UserId: props.info.UserId
    };
    await reqUserBecomeAgent(payload);
    showSuccessToast("设置代理成功");
    show.value = false;
    emit("updateData");
  }, "是否设置该会员为代理？");
};

const updateAndClose = () => {
  emit("updateData");
  show.value = false;
};

defineExpose({
  open() {
    show.value = true;
  }
});
</script>
<style scoped>
.popup-box {
  @apply py-[5px];
}

.popup-box .item {
  @apply h-[50px] text-[14px] text-center leading-[50px] border-solid border-b-[1px] border-[#E4E4E4];
}
</style>
